package com.cdu.practicaltraining.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class DeterministicAesEncryption {

    public static void main(String[] args) {
        String secretKey = "VpV2UosNCVe9pfzo"; // 16字节密钥
        String plainText = "123456";
        String fixedIV = "0123456789abcdef"; // 16字节的固定IV，用于测试

        try {
            String encryptedData = encryptAESWithFixedIV(plainText, secretKey, fixedIV);
            System.out.println("固定IV的加密结果: " + encryptedData);
            System.out.println("解密结果: " + decryptAESWithFixedIV(encryptedData, secretKey));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String encryptAESWithFixedIV(String plainText, String secretKey, String fixedIV) throws Exception {
        // 将固定IV字符串转为字节数组
        byte[] ivBytes = fixedIV.getBytes(StandardCharsets.UTF_8);
        // 将密钥字符串转为字节数组
        byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
        SecretKey key = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivBytes));

        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

        // 组合IV和密文: IV(16字节) + 密文
        byte[] combined = new byte[ivBytes.length + encryptedBytes.length];
        System.arraycopy(ivBytes, 0, combined, 0, ivBytes.length);
        System.arraycopy(encryptedBytes, 0, combined, ivBytes.length, encryptedBytes.length);

        return Base64.getEncoder().encodeToString(combined);
    }

    public static String decryptAESWithFixedIV(String encryptedText, String secretKey) throws Exception {
        // Base64解码整个字符串
        byte[] combined = Base64.getDecoder().decode(encryptedText);

        // 检查长度是否足够包含IV
        if (combined.length < 16) {
            throw new IllegalArgumentException("无效的加密文本：长度不足");
        }

        // 分离IV和加密数据 (前16字节是IV)
        byte[] ivBytes = new byte[16];
        byte[] encryptedBytes = new byte[combined.length - 16];

        System.arraycopy(combined, 0, ivBytes, 0, 16);
        System.arraycopy(combined, 16, encryptedBytes, 0, encryptedBytes.length);

        // 准备密钥
        byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
        SecretKey key = new SecretKeySpec(keyBytes, "AES");

        // 初始化解密器
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivBytes));

        // 执行解密
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}